package com.qys.livesMall.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.open.enums.PushMessageTypeEnum;
import com.qys.livesMall.open.modal.dto.app.PushUserDeviceContentDTO;
import com.qys.livesMall.open.modal.dto.mail.PushAllDeviceDTO;
import com.qys.livesMall.open.modal.dto.mail.PushTitleDTO;
import com.qys.livesMall.open.modal.dto.mail.PushUserDeviceDTO;
import com.qys.livesMall.open.service.PushUserDeviceService;
import com.qys.livesMall.system.enums.SystemMessageEnum;
import com.qys.livesMall.system.model.dto.sys.PlatformInfoDto;
import com.qys.livesMall.system.model.dto.sys.PlatformInfoQueryPackageDto;
import com.qys.livesMall.system.model.entity.H2PlatformInfo;
import com.qys.livesMall.system.mapper.H2PlatformInfoMapper;
import com.qys.livesMall.system.model.vo.sys.PlatformInfoVO;
import com.qys.livesMall.system.service.IH2PlatformInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * <p>
 * 平台信息发布 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-07-05
 */
@Service
public class H2PlatformInfoServiceImpl extends ServiceImpl<H2PlatformInfoMapper, H2PlatformInfo> implements IH2PlatformInfoService {
    @Resource
    private PushUserDeviceService pushUserDeviceService;
    @Resource
    private H2PlatformInfoMapper h2PlatformInfoMapper;
    /**
     * 添加平台信息
     * @param platformInfoDto
     * @return
     */
    @Override
    public boolean add(PlatformInfoDto platformInfoDto) {
        H2PlatformInfo h2PlatformInfo=new H2PlatformInfo();
        BeanUtil.copyProperties(platformInfoDto,h2PlatformInfo);
        h2PlatformInfo.setCreateBy(SecurityUtils.getUsername());
        h2PlatformInfo.setCreateTime(LocalDateTime.now());
        JSONObject jsonTitle=new JSONObject();
        jsonTitle.put("chineseTitle",platformInfoDto.getChineseTitle());
        jsonTitle.put("englishTitle",platformInfoDto.getEnglishTitle());
        h2PlatformInfo.setTitle(jsonTitle.toString());
        JSONObject jsonContent=new JSONObject();
        jsonContent.put("chinese",platformInfoDto.getChineseContent());
        jsonContent.put("english",platformInfoDto.getEnglishContent());
        h2PlatformInfo.setContent(jsonContent.toString());
        save(h2PlatformInfo);
        if (platformInfoDto.getTypeInfo() == 0 || (platformInfoDto.getTypeInfo() == 1 && platformInfoDto.getTarget().equals("4"))){
            //推送全部用户
            this.PushinfoToAll(h2PlatformInfo);
        }else {
            //推送指定用户
            this.PushinfoToUser(h2PlatformInfo);
        }

        return true;
    }

    /**
     * 修改平台信息
     * @param platformInfoDto
     * @return
     */
    @Override
    public boolean update(PlatformInfoDto platformInfoDto) {
        H2PlatformInfo h2PlatformInfo=getById(platformInfoDto.getId());
        if (null == h2PlatformInfo){
            throw new QysException(SystemMessageEnum.SYSTEM_NOT_ID);
        }
        Byte type=h2PlatformInfo.getType();
        BeanUtil.copyProperties(platformInfoDto,h2PlatformInfo);
        h2PlatformInfo.setUpdateBy(SecurityUtils.getUsername());
        h2PlatformInfo.setUpdateTime(LocalDateTime.now());
        h2PlatformInfo.setType(type);
        JSONObject jsonTitle=new JSONObject();
        jsonTitle.put("chineseTitle",platformInfoDto.getChineseTitle());
        jsonTitle.put("englishTitle",platformInfoDto.getEnglishTitle());
        h2PlatformInfo.setTitle(jsonTitle.toString());
        JSONObject jsonContent=new JSONObject();
        jsonContent.put("chinese",platformInfoDto.getChineseContent());
        jsonContent.put("english",platformInfoDto.getEnglishContent());
        h2PlatformInfo.setContent(jsonContent.toString());
        updateById(h2PlatformInfo);
        if (platformInfoDto.getTypeInfo() == 0 || (platformInfoDto.getTypeInfo() == 1 && platformInfoDto.getTarget().equals("4"))){
            //推送全部用户
            this.PushinfoToAll(h2PlatformInfo);
        }else {
            //推送指定用户
            this.PushinfoToUser(h2PlatformInfo);
        }
        return true;
    }

    /**
     * 推送指定用户信息
     * @param h2PlatformInfo
     * @return
     */
    public void PushinfoToUser(H2PlatformInfo h2PlatformInfo){
        PushUserDeviceDTO pushUserDeviceDTO=new PushUserDeviceDTO();
        PushTitleDTO pushTitleDTO=new PushTitleDTO();
        JSONObject jsonTitle= JSON.parseObject(h2PlatformInfo.getTitle());
        pushTitleDTO.setChinese(jsonTitle.get("chineseTitle").toString());
        pushTitleDTO.setEnglish(jsonTitle.get("englishTitle").toString());
        pushUserDeviceDTO.setTitle(pushTitleDTO);
        if (StringUtil.isNotBlank(h2PlatformInfo.getPushTarget()) && h2PlatformInfo.getTarget().equals("6")){
            String[] arr = h2PlatformInfo.getPushTarget().split(",");
            List<Long> userIds=new ArrayList<>();
            for (String userid:arr){
                userIds.add(Long.valueOf(userid));
            }
            pushUserDeviceDTO.setUserIds(userIds);
        }else {
            String[] targets= h2PlatformInfo.getTarget().split(",");
            Set<Long> setuser=new HashSet<>();
            for (String str:targets){
                String[] arr = h2PlatformInfo.getPushTarget().split(",");
                List<Long> userids= h2PlatformInfoMapper.getUserid(str,arr);
                setuser.addAll(userids);
            }
            pushUserDeviceDTO.setUserIds(new ArrayList<>(setuser));
        }
        PushUserDeviceContentDTO pushUserDeviceContentDTO=new PushUserDeviceContentDTO();
        if (h2PlatformInfo.getTypeInfo().intValue()==0){
            pushUserDeviceContentDTO.setType(PushMessageTypeEnum.NOTICE);
        }else {
            pushUserDeviceContentDTO.setType(PushMessageTypeEnum.PUSH);
        }
        pushUserDeviceContentDTO.setData(h2PlatformInfo.getContent());
        pushUserDeviceDTO.setContent(pushUserDeviceContentDTO);
        pushUserDeviceService.pushUserDevice(pushUserDeviceDTO);
    }

    /**
     * 推送全部用户信息
     * @param h2PlatformInfo
     * @return
     */
    public void PushinfoToAll(H2PlatformInfo h2PlatformInfo){
        PushAllDeviceDTO pushAllDeviceDTO=new PushAllDeviceDTO();
        PushTitleDTO pushTitleDTO=new PushTitleDTO();
        JSONObject jsonTitle= JSON.parseObject(h2PlatformInfo.getTitle());
        pushTitleDTO.setChinese(jsonTitle.get("chineseTitle").toString());
        pushTitleDTO.setEnglish(jsonTitle.get("englishTitle").toString());
        pushAllDeviceDTO.setTitle(pushTitleDTO);
        PushUserDeviceContentDTO pushUserDeviceContentDTO=new PushUserDeviceContentDTO();
        if (h2PlatformInfo.getTypeInfo().intValue()==0){
            pushUserDeviceContentDTO.setType(PushMessageTypeEnum.NOTICE);
        }else {
            pushUserDeviceContentDTO.setType(PushMessageTypeEnum.PUSH);
        }
        pushUserDeviceContentDTO.setData(h2PlatformInfo.getContent());
        pushAllDeviceDTO.setContent(pushUserDeviceContentDTO);
        pushUserDeviceService.pushAllUserDevice(pushAllDeviceDTO);
    }
    /**
     * 查询平台信息列表
     * @param dto
     * @return
     */
    @Override
    public IPage<PlatformInfoVO> query(PlatformInfoQueryPackageDto dto) {
        LambdaQueryWrapper<H2PlatformInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(H2PlatformInfo::getDeleted, 0);
        queryWrapper.eq(H2PlatformInfo::getType, dto.getType());
        queryWrapper.eq(H2PlatformInfo::getTypeInfo, dto.getTypeInfo());
        queryWrapper.and(StringUtil.isNotBlank(dto.getTitle()), wrapper->{
            wrapper.like(H2PlatformInfo::getTitle, dto.getTitle());
            wrapper.or().like(H2PlatformInfo::getContent, dto.getTitle());
        });
        queryWrapper.ge(null!=dto.getStartTime(),H2PlatformInfo::getCreateTime,dto.getStartTime());
        queryWrapper.le(null!=dto.getEndTime(),H2PlatformInfo::getCreateTime,dto.getEndTime());
        queryWrapper.orderByDesc(H2PlatformInfo::getCreateTime);
        IPage<PlatformInfoVO> page=page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper).convert(e -> {
            PlatformInfoVO navyLanguageManageVo=new PlatformInfoVO();
            BeanUtils.copyProperties(e,navyLanguageManageVo);
            navyLanguageManageVo.setCreatelongtime(e.getCreateTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
            JSONObject jsonTitle= JSON.parseObject(e.getTitle());
            navyLanguageManageVo.setChineseTitle(jsonTitle.get("chineseTitle").toString());
            navyLanguageManageVo.setEnglishTitle(jsonTitle.get("englishTitle").toString());
            e.setTitle(jsonTitle.toString());
            JSONObject jsonContent= JSON.parseObject(e.getContent());
            navyLanguageManageVo.setChineseContent(jsonContent.get("chinese").toString());
            navyLanguageManageVo.setEnglishContent(jsonContent.get("english").toString());
            e.setContent(jsonContent.toString());
            return navyLanguageManageVo;
        });
        return page;
    }

    /**
     * 根据ID 查询详情
     * @param id
     * @return
     */
    @Override
    public PlatformInfoVO info(Long id) {
        H2PlatformInfo h2PlatformInfo=getById(id);
        if (null == h2PlatformInfo){
            throw new QysException(SystemMessageEnum.SYSTEM_NOT_ID);
        }
        PlatformInfoVO navyLanguageManageVo=new PlatformInfoVO();
        BeanUtils.copyProperties(h2PlatformInfo,navyLanguageManageVo);
        navyLanguageManageVo.setCreatelongtime(h2PlatformInfo.getCreateTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        JSONObject jsonTitle= JSON.parseObject(h2PlatformInfo.getTitle());
        navyLanguageManageVo.setChineseTitle(jsonTitle.get("chineseTitle").toString());
        navyLanguageManageVo.setEnglishTitle(jsonTitle.get("englishTitle").toString());
        h2PlatformInfo.setTitle(jsonTitle.toString());
        JSONObject jsonContent= JSON.parseObject(h2PlatformInfo.getContent());
        navyLanguageManageVo.setChineseContent(jsonContent.get("chinese").toString());
        navyLanguageManageVo.setEnglishContent(jsonContent.get("english").toString());
        h2PlatformInfo.setContent(jsonContent.toString());
        return navyLanguageManageVo;
    }
}
